<template>
  <div>
    <el-button @click="clear">清除标注</el-button>
    <div id="container" ref="mapContainer" class="map-container" @getZoom="getZoom"></div>
  </div>

</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
const logisticsInfoList = [
  { latitude: '31.8877', longitude: '117.46928' },
  { latitude: '31.71369', longitude: '117.16324' },
  { latitude: '32.43522', longitude: '117.18092' }
];
export default {
  props: {
    mapActive: Number
  },
  data() {
    return {
      //此处不声明 map 对象，可以直接使用 this.map赋值或者采用非响应式的普通对象来存储。
      map: null,
      stationId: '807',
      itemId: '',
      dateTime: '2023-08-15',
      mapDataMarker: [],//图层级变化点数量个数变化
      visiblePoints: [], //初始值展示前40个
      allPoints: [], // 全部值
      points: [],
      // iconPath1: require('../../../../../assets/images/icon-screen-frame.png'),
      // iconPath2: require('../../../../../assets/images/icon-screen-station.png'),
      // iconPath: require('../../../../../assets/images/icon-screen-station.png'),
      zoom: 7.2,
      nameArr: []
    };
  },
  mounted() {
    // 查询门架OR收费站经纬度
    // this.getGantryStationData(this.mapActive)
    this.$nextTick(() => {
      this.initMap();
    });
  },
  watch: {
    mapActive: {
      deep: true,
      handler(value) {
        this.mapActive = value
        if (this.mapActive == 0) {
          this.iconPath = this.iconPath1
        } else {
          this.iconPath = this.iconPath2
        }
        this.getGantryStationData(this.mapActive)
      }
    }
  },
  methods: {
    getZoom(event) {
      console.log("event:", event)
    },
    // 根据地图缩放大小渲染点
    drawMarkerByZoom(val) {
      let that = this;
      // 清空标记点
      that.map.remove(that.mapDataMarker)
      let len = 120; // 渲染点初始值
      let zoom = val || 7.2;
      console.log("zoom:::", zoom, typeof (zoom))
      if (zoom < 7) {
        len = 120
      } else if (zoom >= 7 && zoom < 7.5) {
        len = 160
      } else if (zoom >= 7.5 && zoom < 8) {
        len = 180
      } else {
        len = that.allPoints.length
      }
      that.points = that.allPoints.slice(0, len)
      // 循环渲染到地图上
      const markers = []
      that.points.map(item => {
        let obj = {}  //存放lnglat[lng,lat]
        obj.position = [Number(item.LNG), Number(item.LAT)]
        obj.stationId = item.STATIONID,
          obj.itemId = item.ID,
          obj.NAME = item.NAME

        markers.push(obj)
      })
      // for (var i = 0, marker; i < markers.length; i++) {
      // 	var marker = new AMap.Marker({
      // 		icon: new AMap.Icon({
      // 			image: that.iconPath,
      // 			size: new AMap.Size(24, 27),  //图标大小
      // 			imageSize: new AMap.Size(24, 27)
      // 		}),
      // 		position: markers[i].position,
      // 		map: that.map,
      // 		offset: new AMap.Pixel(-13, -30),
      // 		stationId: markers[i].stationId,
      // 		itemId: markers[i].itemId,
      // 		NAME: markers[i].NAME
      // 	});
      // 	that.mapDataMarker.push(marker)
      // 	marker.on("click", markerClick);
      // 	// 获取点击后的id
      // 	function markerClick(e) {
      // 		console.log('e', e);
      // 		that.$emit("getStationId", e.target.w.stationId, e.target.w.itemId, e.target.w.NAME)
      // 	}
      // }
    },
    initMap() {
      // 模拟后端返回的坐标（道路）
      var pointsArr = [//每个弧线段有两种描述方式
        [117.283042, 31.86119],//起点
        //第一段弧线
        [117.283042, 31.86119,118.383042, 32.86119, 118.583042, 31.86119, ],//控制点，途经点
        //第二段弧线
        [116.5005646164, 31.7470318307, 116.9701538, 33.6401329,],//控制点，途经点//弧线段有两种描述方式1
    ];
      const that = this;
      AMapLoader.load({
        key: "4f11282ac15035205ac4066d1a81003a", // 申请好的Web端开发者Key，首次调用 load 时必填
        // version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          "AMap.DistrictSearch",
          "AMap.TileLayer",
          "AMap.ControlBar",
          "AMap.DistrictLayer",
          "AMap.Driving",
          "AMap.BezierCurve"

        ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          let opts = {
            subdistrict: 0,
            extensions: "all",
            level: "district",
          };
          //利用行政区查询获取边界构建mask路径
          //也可以直接通过经纬度构建mask路径
          let district = new AMap.DistrictSearch(opts);
          let mask = [];
          let bounds = [];
          district.search("安徽省", (status, result) => {
            bounds = result.districtList[0].boundaries;
            // mask = [];
            for (var i = 0; i < bounds.length; i += 1) {
              mask.push([bounds[i]]);
            }
            var disCountry = new AMap.DistrictLayer.Country({
              // zIndex: 10,
              // SOC: "CHN",
              // depth: 1,
              styles: {
                // "nation - stroke": "#fff",
                // "coastline - stroke": "#fff",
                // "province - stroke": "#fff",
                fill: (props) => {
                  // return 'rgba(255, 255, 255, 0.9)'
                  return "#267AD0"; //修改地图的颜色为透明色
                },
              },
            });
            this.map = new AMap.Map("container", {
              // resizeEnable: false,
              mask: mask,
              center: [117.283042, 31.86119],
              viewMode: "3D",
              // showLabel: false,
              showLabel: true, //显示地名
              labelzIndex: 130,
              // dragEnable: false,
              // pitch: 40,
              zoom: 7.2,
              layers: [
                // disCountry
              ],
            });
            let maskerIn = new AMap.Marker({
              position: [116.501415, 39.926055],
              map: this.map,
            });
            let maskerOut = new AMap.Marker({
              //区域外的不会显示
              position: [117.001415, 39.926055],
              map: this.map,
            });
            var trafficLayer = new AMap.TileLayer.Traffic({
              zIndex: 10,
              zooms: [7, 20]
            })
            trafficLayer.setMap(this.map)
            //添加描边
            console.log(bounds);
            for (var i = 0; i < pointsArr.length; i += 1) {
              // const arr = [];
              // pointsArr[i].forEach(item=>{
              //   arr.push(new AMap.LngLat(item[0], item[1]))
              // })
              new AMap.BezierCurve({
                path: pointsArr,
                strokeOpacity: 0.5, // 线透明度
                strokeWeight: 2,
                strokeColor: '#3366FF',
                borderWeight: 1,
                map: this.map,
                lineJoin: 'round',
                lineCap: 'round',
                outlineColor: '#ffeeff',
                isOutline: true,
              });
              
            }
            this.map.setMapStyle("amap://styles/blue");
            let outer = [
              new AMap.LngLat(-360, 90, true),
              new AMap.LngLat(-360, -90, true),
              new AMap.LngLat(360, -90, true),
              new AMap.LngLat(360, 90, true),
            ];
            let holes = result.districtList[0].boundaries;
            let pathArray = [outer];
            pathArray.push.apply(pathArray, holes);
            let polygon = new AMap.Polygon({
              pathL: pathArray,
              strokeColor: "#000000", //城市边界颜色
              strokeWeight: 1,
              fillColor: "#000000", // 遮罩背景色黑色
              fillOpacity: 0.6,
            });
            polygon.setPath(pathArray);
            this.map.add(polygon);
            // 地图上的图标
            // 3D控制板
            // this.map.addControl(
            //   new AMap.ControlBar({
            //     showZoomBar: true,
            //     showControlButton: true,
            //     position: {
            //       right: "10px",
            //       top: "10px",
            //     },
            //   })
            // );

            that.drawMarkerByZoom(7.2)//初始调用marker过滤方法。
            this.map.on("zoomchange", function (e) {
              console.log(e.target.getZoom());
              //清除地图上点位信息
              for (let i = that.mapDataMarker.length - 1; i >= 0; i--) {
                that.mapDataMarker[i].setMap(null);
              }
              that.mapDataMarker = [];
              // 获取缩放比例
              // let val = e.target.getZoom()
              // that.drawMarkerByZoom(val)
            });
           
          });
        })
        .catch((e) => {
          console.log("报错", e);
        });
    },
    getGantryStationData(dataType) {
      // if (dataType == 1) {
      // 	selectGantryStation().then(res => {
      // 		if (res.code == '200' && res.data.code == '0000') {
      // 			const query = JSON.parse(res.data.data)
      // 			this.allPoints = query
      // 			this.visiblePoints = this.allPoints.slice(0, 4)
      // 			this.points = this.visiblePoints
      // 			this.drawMarkerByZoom()
      // 		}
      // 	})
      // } else {
      // 	selectGantryInfo().then(res => {
      // 		if (res.code == '200' && res.data.code == '0000') {
      // 			const query = JSON.parse(res.data.data)
      // 			this.allPoints = query
      // 			this.visiblePoints = this.allPoints.slice(0, 4)
      // 			this.points = this.visiblePoints
      // 			this.drawMarkerByZoom()
      // 		}
      // 	})

      // }
    },

    clear() {
      console.log('clear', this.map);
      this.map.clearMap();
    },
    // 坐标分组(用于计算路径坐标)
    getGroup(arr) {
      let newArr = [];
      newArr.push(arr[0])
      arr.shift()
      while (arr.length > 0) {  
        newArr.push(arr.splice(0, 2));  
      }
      return newArr;
    },
  },
};
</script>

<style lang="scss" scoped>
#container {
  padding: 0px;
  margin: 0px;
  width: 800px;
  height: 800px;
  background: rgba(0, 0, 0, 0) !important;
}

::v-deep .amap-info-content {
  color: #000;
}
</style>